import { ChangeDetectorRef, Component, ElementRef, NgZone, ViewChild } from '@angular/core';
import {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y';

@Component({
  selector: 'app-monitoring-focus',
  templateUrl: './monitoring-focus.component.html',
  styleUrls: ['./monitoring-focus.component.sass']
})
export class MonitoringFocusComponent {
  @ViewChild('monitored', {static: true}) monitoredEl: ElementRef<HTMLElement>;

  elementOrigin = this.formatOrigin(null);
  subtreeOrigin = this.formatOrigin(null);

  formatOrigin(origin: FocusOrigin): string {
    return origin ? origin + ' focused' : 'blurred';
  }

  // Workaround for the fact that (cdkFocusChange) emits outside NgZone.
  markForCheck() {
    this._ngZone.run(() => this._cdr.markForCheck());
  }

  origin = this.formatOrigin(null);

  constructor(public focusMonitor: FocusMonitor,
              private _cdr: ChangeDetectorRef,
              private _ngZone: NgZone) {}

  ngAfterViewInit() {
    this.focusMonitor.monitor(this.monitoredEl)
        .subscribe(origin => this._ngZone.run(() => {
          this.origin = this.formatOrigin(origin);
          this._cdr.markForCheck();
        }));
  }

  ngOnDestroy() {
    this.focusMonitor.stopMonitoring(this.monitoredEl);
  }

}
